package com.example.demo.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.custom.BaseController;
import com.example.demo.entity.BanZu;
import com.example.demo.entity.SysDept;
import com.example.demo.entity.SysRole;
import com.example.demo.entity.SysUser;
import com.example.demo.form.SysUserForm;
import com.example.demo.security.UserUtils;
import com.example.demo.service.BanZuService;
import com.example.demo.service.PositionService;
import com.example.demo.service.SysRoleService;
import com.example.demo.service.SysUserService;

@RestController
@RequestMapping(value = "/user")
public class SysUserController extends BaseController<SysUser, Integer, SysUserForm> {
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysUserService service;
    @Autowired
    private PositionService zhiweiservice;
    @Autowired
    private BanZuService banzuservice;
	@Autowired
	private UserUtils userUtils;
    

    @RequestMapping(value="/findById")
	public Object byId(SysUserForm form) {
    	SysUser model = null;
		Integer id = form.getId();
		if(id!=null) {
			 model = service.findById(id);
		}	
		return new AjaxResult(model);	
	}
    
	@RequestMapping(value = "/resetPwd")
	@ResponseBody
	public Object resetPwd(Integer id,String strName) {
		SysUser model = service.findById(id);
		model.setPassword(new BCryptPasswordEncoder().encode(strName));
		service.save(model);
		return new AjaxResult(strName);
	}
    
    @SuppressWarnings("serial")
    @Override
    public Specification<SysUser> buildSpec(SysUserForm form) {
        Specification<SysUser> spec = new Specification<SysUser>() {

            @Override
            public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                HashSet<Predicate> rules = new HashSet<>();
                String username = form.getUsername();
                if (StringUtils.hasText(username)) {
                    rules.add(cb.like(root.get("username"), "%" + username + "%"));
                }
                String name = form.getName();
                if (StringUtils.hasText(name)) {
                    rules.add(cb.like(root.get("name"), "%" + name + "%"));
                }
                String deptName = form.getDeptName();
                if (StringUtils.hasText(deptName)) {
                    rules.add(cb.like(root.get("dept").get("name"), "%" + deptName + "%"));
                }
                String search = form.getSearch();
                if (StringUtils.hasText(search)) {
                    HashSet<Predicate> rules2 = new HashSet<>();
                    rules2.add(cb.like(root.get("username"), "%" + search + "%"));
                    rules2.add(cb.like(root.get("name"), "%" + search + "%"));
                    rules2.add(cb.like(root.get("dept").get("name"), "%" + search + "%"));
                    rules.add(cb.or(rules2.toArray(new Predicate[rules2.size()])));
                }
                return cb.and(rules.toArray(new Predicate[rules.size()]));
            }
        };
        return spec;
    }

    @Override
    public Object save(SysUserForm form) {
        try {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            SysUser model = new SysUser();
            Integer id = form.getId();
            if (id != null) {
                model = service.findById(id);
            } else {
                if(form.getBanzu()!=null&&form.getBanzu().length()>0) {
                	BanZu banzu =new BanZu();
                	List<BanZu> banzus = banzuservice.findAll();
                	for(BanZu ban:banzus) {
                		if(!form.getBanzu().equals(ban.getName())) {
                			banzu.setName(form.getBanzu());
                		}else {
                			banzu=banzuservice.findByName(form.getBanzu());
                		}
                	}
                	banzu.setName(form.getBanzu());
                	banzuservice.save(banzu);
                	model.setBanzu(banzu);
                }
                for (SysUser sysUser : service.findAll()) {
					if(form.getUsername().equals(sysUser.getUsername())) {
						return new AjaxResult(false, "用户名已存在！");
					}
				}
                model.setPassword(encoder.encode("1234"));
            }
            Integer deptId = form.getDeptId();
            if (deptId != null) {
                model.setDept(new SysDept(deptId));
            }
            Integer zhiweiId = form.getZhiweiId();
            if (zhiweiId != null) {
                model.setZhiwei(zhiweiservice.findById(zhiweiId));
            }

            List<SysRole> roles = new ArrayList<>();
            String rolestr = form.getRoles();
            for (String code : rolestr.split(",")) {
                roles.add(roleService.findById(Integer.parseInt(code)));
            }
            model.setRoles(roles);
            BeanUtils.copyProperties(form, model, "id", "dept", "roles","zhiwei","banzuId","banzu");
            service.save(model);
            return new AjaxResult("数据保存成功");
        } catch (Exception e) {
            return new AjaxResult(false, "数据保存失败");
        }
    }

    
    @Override
    public void edit(SysUserForm form, ModelMap modelMap) throws InstantiationException, IllegalAccessException {
        List<SysRole> roles = roleService.findByParent(null);
        modelMap.put("roles", roles);
        super.edit(form, modelMap);
    }

    @RequestMapping(value = "/getuser")
    public Object getuser(){
   SysUser user = service.findById(userUtils.getUser().getId());
   return new AjaxResult(user);
    }
    
    @RequestMapping(value = "/banzu")
    public Object getBanZu() {
    	List<BanZu> list = banzuservice.findAll();
    	return new AjaxResult(list);
    }
    @RequestMapping(value = "/findByBanZu")
    public Object getJishi(Integer id) {
    	BanZu banzu = banzuservice.findById(id);
    	List<SysUser> users = service.findByBanZu(banzu);
    	return new AjaxResult(users);
    }
}
